package com.bfb.helpers;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.util.Base64;
import android.util.Log;

import com.bfb.Main;

/**
 * Helper class for functionalities related to the dish that require server
 * contact.
 * 
 * @author Rawan Khalil (rawan.tkhalil@gmail.com)
 * 
 */
public class Dishes {

	/**
	 * Contacts the server by using an {@link HttpGet} with the url path being
	 * "/dishes/all". The response is received in an {@link HttpResponse} that
	 * is a {@link JSONArray} containing the list of all the dishes in the db.
	 * The result is returned as an {@link ArrayList} of all the dish names.
	 * 
	 * @return {@link ArrayList}
	 * 
	 * @author Rawan Khalil (rawan.tkhalil@gmail.com)
	 */
	public static ArrayList<String> getAll() {
		ArrayList<String> dishNames = new ArrayList<String>();
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet("http://" + Main.SERVER
					+ "/dishes/all");
			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				HttpEntity entity = response.getEntity();
				JSONArray jsonArray = new JSONArray(
						ServerUtilities.getContentFromStream(entity
								.getContent()));
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					dishNames.add(jsonObject.getString("name"));
				}
			} else
				throw new Exception("Response NULL");
		} catch (Exception e) {
			Log.e("Dishes_GetAll", e.getMessage(), e);
		}
		return dishNames;
	}

	/**
	 * Contacts the server by using {@link HttpPost} to send the data of the
	 * newly created dish to the server. The data is sent in a list of
	 * {@link NameValuePair}. The image of the dish is scaled down and
	 * compressed and then converted to {@link Base64} in order to be sent to
	 * the server at which it is decoded.
	 * 
	 * @param dishName
	 *            The dish name
	 * @param dishType
	 *            The dish type
	 * @param restaurantName
	 *            The restaurant name
	 * @param restaurantIsNew
	 *            Whether the restaurant is in the db or not
	 * @param latitudes
	 *            Latitudes of the restaurant locations
	 * @param longitudes
	 *            Longitudes of the restaurant locations
	 * @param dishRating
	 *            The dish rating
	 * @param ingredients
	 *            The list of ingredients
	 * @param dishImage
	 *            The {@link Bitmap} image of the dish
	 * 
	 * @author Rawan Khalil (rawan.tkhalil@gmail.com)
	 * 
	 */
	public static void create(final String dishName, final String dishType,
			final String restaurantName, final double[] longitudes,
			final double[] latitudes, final String restaurantIsNew,
			final float dishRating, final ArrayList<String> ingredients,
			final Bitmap dishImage) {
		ServerUtilities.background(new Runnable() {
			@Override
			public void run() {
				try {
					DefaultHttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://" + Main.SERVER
							+ "/dishes/new");

					Bitmap resizedDishImage = Bitmap.createScaledBitmap(
							dishImage, 150, 150, false);
					ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
					resizedDishImage.compress(Bitmap.CompressFormat.PNG, 90,
							byteStream);
					String dishImageString = Base64.encodeToString(
							byteStream.toByteArray(), Base64.DEFAULT);

					String longitudesString = "";
					String latitudesString = "";
					if (longitudes != null && longitudes.length != 0) {
						int longitudesLength = longitudes.length - 1;
						for (int i = 0; i < longitudesLength; i++) {
							longitudesString += longitudes[i] + "#";
							latitudesString += latitudes[i] + "#";
						}
						longitudesString += longitudes[longitudesLength];
						latitudesString += latitudes[longitudesLength];
					}

					ArrayList<NameValuePair> nvpList = new ArrayList<NameValuePair>();
					nvpList.add(new BasicNameValuePair("dishName", dishName));
					nvpList.add(new BasicNameValuePair("dishType", dishType));
					nvpList.add(new BasicNameValuePair("restaurantName",
							restaurantName));
					nvpList.add(new BasicNameValuePair("isNewRestaurant",
							restaurantIsNew));
					nvpList.add(new BasicNameValuePair("longitudes",
							longitudesString));
					nvpList.add(new BasicNameValuePair("latitudes",
							latitudesString));
					nvpList.add(new BasicNameValuePair("dishRating", dishRating
							+ ""));
					nvpList.add(new BasicNameValuePair("dishImage",
							dishImageString));
					nvpList.add(new BasicNameValuePair("ingredients",
							ingredients.toString()));

					httppost.setEntity(new UrlEncodedFormEntity(nvpList));

					HttpResponse response = httpClient.execute(httppost);

					if (response == null) {
						throw new Exception("Response NULL");
					}
				} catch (Exception e) {
					Log.e("Post new dish", e.getMessage(), e);
				}
			}
		});
	}

}
